package com.indusfo.spc.aop;

import com.indusfo.spc.pojo.Log;
import com.indusfo.spc.pojo.User;
import com.indusfo.spc.service.LogService;
import com.indusfo.spc.untlis.GsonUtil;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author: 熊冰
 * @Date: 2020/1/4 13:57
 */

@Aspect
@Component
public class LogAop {

//	private static final Logger logger = LoggerFactory.getLogger(LogAop.class);


	@Resource
	private LogService logService;
/**
 * @Author 熊冰 //切入点描述 这个是controller包的切入点
 * @Date 2020/1/4 13:58
 */
	@Pointcut("execution(public * com.indusfo.spc.controller..*.*(..))")
	public void controllerLog(){}



	@Around("controllerLog()")
	public Object AfterAroundM(ProceedingJoinPoint point) {
		try {
//			System.out.println("环绕通知前");
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			//获取参数数组
			Object[] args = point.getArgs();
//			执行原方法并获取返回结果
			Object ret = point.proceed(args);
//			StringBuilder sb = new StringBuilder();
//			sb.append("   ###请求URL: " + request.getRequestURL().toString());
//			sb.append("   ###IP: " + request.getRemoteAddr());
//			sb.append("   ###入参: " + Arrays.toString(args));
//			sb.append("   ###方法: " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
//
//			System.out.println("   ###请求URL: " + request.getRequestURL().toString());
//			System.out.println("   ###IP: " + request.getRemoteAddr());

//			System.out.println("   ###入参: "+GsonUtil.toJson(args));
//			System.out.println("   ###方法: " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());

			//判断执行的动作
			String pointName=point.getSignature().getName();
			String pointNameCut="";
			if(checkString(pointName)){
				pointNameCut=getString(pointName);
			}else{
				pointNameCut=pointName;
			}


			String description="";
			switch(pointNameCut){
				case "query" :
					//语句
					description="查询";
					break;
				case "select" :
					//语句
					description="查询";
					break;
				case "insert" :
					//语句
					description="新增";
					break;
				case "update" :
					//语句
					description="修改";
					break;
				case "defined" :
					//语句
					description="启用/停用";
					break;
				case "delete" :
					//语句
					description="删除";
					break;
				case "upload" :
					//语句
					description="导入";
					break;
				case "tree" :
					//语句
					description="查询";
					break;
				case "save" :
					//语句
					description="保存";
					break;
				case "copy" :
					//语句
					description="保存";
					break;
				case "login" :
					//语句
					description="登陆";
					break;
				case "array" :
					//语句
					description="查询";
					break;
				//你可以有任意数量的case语句
				default :
					//语句
					description="未知";
					break;
			}

			String pointUrl=request.getRequestURL().toString();
			String str1=pointUrl.substring(0, pointUrl.lastIndexOf("/"));
			String pointModel=str1.substring(str1.lastIndexOf("/")+1);



//			System.out.println("   ###路径: " + pointUrl);
//			System.out.println("   ###IP: " + request.getRemoteAddr());
//			System.out.println("   ###模块: " + pointModel);
//			System.out.println("   ###动作: " + pointName);
//			System.out.println("   ###按钮: " + description);
//			Object s =request.getSession().getAttribute("user");
//			String us=GsonUtil.toJson(s);
			Integer uid=1;
//			String rm=GsonUtil.toJson(args);
//			if (us!=null){
//				int p=us.indexOf(":"), pi=0,ppi=0;
//				int q=us.indexOf(","), qi=0,qqi=0;
//				while(p>-1){
//					pi++;
//					if(pi==2){
//						ppi=p;
//						break;
//					}
//					p=us.indexOf(":", p+1);
//				}
//				while(q>-1){
//					qi++;
//					if(qi==1){
//						qqi=q;
//						break;
//					}
//					q=us.indexOf(",", q+1);
//				}
//				System.out.printf(us.substring(ppi+1, qqi));
//				uid=Integer.parseInt(us.substring(ppi+1, qqi));
//			}

			if(!(description.equals("查询")||description.equals("树"))){
				if(description.equals("删除")||description.equals("新增")||description.equals("修改")){



					Log log=new Log();
					log.setLogIp(request.getRemoteAddr());
					log.setLogAction(pointName);
					log.setLogButton(description);
					log.setLogModel(pointModel);
					log.setLogUrl(pointUrl);
					log.setUserId(uid);
					log.setRemark("");
					logService.insertLog(log);



				}else if(description.equals("登陆")){
					Log log=new Log();
					log.setLogIp(request.getRemoteAddr());
					log.setLogAction(pointName);
					log.setLogButton(description);
					log.setLogModel(pointModel);
					log.setLogUrl(pointUrl);
					log.setUserId(uid);
					log.setRemark("");
					logService.insertLog(log);
				}else{
					Log log=new Log();
					log.setLogIp(request.getRemoteAddr());
					log.setLogAction(pointName);
					log.setLogButton(description);
					log.setLogModel(pointModel);
					log.setLogUrl(pointUrl);
					log.setUserId(uid);
					log.setRemark("");
					logService.insertLog(log);
				}

			}


//            int q=1/0;
//			System.out.println("环绕通知返回");
			return	ret;
		} catch (Throwable throwable) {
			throwable.printStackTrace();
//			System.out.println("环绕通知异常");
		} finally {

//			System.out.println("环绕通知后");
		}
		return	null;
	}

	public static String getString(String str){
		int index = -1;
		char[] chars = str.toCharArray();
		for(int i=0; i<chars.length; i++){
			if((chars[i] >= 'A') && (chars[i] <= 'Z')){
				index = i;
				break;
			}
		}
		return str.substring(0, index);
	}
	private static boolean checkString(String str){
		char ch;
		boolean capitalFlag = false;
		boolean lowerCaseFlag = false;
		boolean numberFlag = false;
		for(int i = 0; i< str.length();i ++){
			ch = str.charAt(i);
			if(Character.isDigit(ch)){
				numberFlag = true;
			}
 				else if(Character.isUpperCase(ch)){
				capitalFlag = true;
			} else if(Character.isLowerCase(ch)){
				lowerCaseFlag = true;
			}
 			if(capitalFlag){
 				return true;
			}

		}
		return false;
	}

//	@After("controllerLog()")
//	public void doAfter(JoinPoint point) throws Throwable {
//		// 接收到请求，记录请求内容
//		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//		HttpServletRequest request = attributes.getRequest();
//		//获取参数数组
//			Object[] args = point.getArgs();
//			//执行原方法并获取返回结果
//			//			Object ret = point.proceed(args);
//			StringBuilder sb = new StringBuilder();
//			sb.append("   ###请求URL: " + request.getRequestURL().toString());
//			sb.append("   ###IP: " + request.getRemoteAddr());
//			sb.append("   ###入参: " + Arrays.toString(args));
//			sb.append("   ###方法: " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
//
//			System.out.println("   ###请求URL: " + request.getRequestURL().toString());
//			System.out.println("   ###IP: " + request.getRemoteAddr());
//			System.out.println("   ###入参: " + Arrays.toString(args));
//			System.out.println("   ###方法: " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
//
//		// 记录下请求内容
////		logger.info("URL : " + request.getRequestURL().toString());
////		logger.info("HTTP_METHOD : " + request.getMethod());
////		logger.info("IP : " + request.getRemoteAddr());
////		logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
////		logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
//	}



}
